package org.capgemini.tienda.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class MySQLDAOFactory extends DAOFactory{
	
	private static Connection connection;
	private static ResourceBundle dbParams = ResourceBundle.getBundle("org.capgemini.tienda.dao.MySQLDAOFactory");
	private static String URL = "DATASOURCE.URL";
	private static String DRIVER = "DATASOURCE.DRIVER";
	private static String USER = "DATASOURCE.USER";
	private static String PASS = "DATASOURCE.PASS";
	
	private static Connection createConnection() {
		try {
			if(connection==null){
				Class.forName(dbParams.getString(DRIVER));
				connection = DriverManager.getConnection(dbParams.getString(URL), dbParams.getString(USER), dbParams.getString(PASS));
			}
			
		} catch (ClassNotFoundException e) {
			
			e.printStackTrace();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		return connection;
	}

	public void desconectar()  {
		try {
			connection.close();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
	}

	public Connection getConnection() {
		return connection;
	}

	/**
	 * Constructor por defecto de la clase
	 */
	public MySQLDAOFactory() {
		//createConnection();
	}
	
	@Override
	public IProductosDAO getProductosDAO() {
		return new MySqlProductosDAO(createConnection());
	}

	@Override
	public IUsuariosDAO getUsuariosDAO() {
		return new MySqlUsuariosDAO(createConnection());
	}
	
	public static void main(String[] args) {
		System.out.println(DAOFactory.getDAOFactory(DAOFactory.MYSQL).getUsuariosDAO().existeUsername("admin"));
	}
}
